<template>
  <div class="wb-main">
    <el-form
      ref="dataForm"
      :model="dataForm"
      label-width="100px"
    >
      <el-form-item
        label="品牌"
        :rules="[
          { required: true, message: '品牌不能为空'},
        ]"
      >
        <el-select
          v-model="dataForm.brandId"
          style="width: 250px"
          placeholder="请选择"
        >
          <el-option
            v-for="item in brandList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品图片">
        <mul-pic-upload v-model="dataForm.imgs" />
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item
        label="产品分类"
        :rules="[{ required: true, message: '请选择产品分类'}]"
        prop="categoryId"
      >
        <el-col :span="8">
          <el-cascader
            v-model="category.selected"
            expand-trigger="hover"
            :options="category.list"
            :props="category.props"
            change-on-select
            @change="handleCategoryChange"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="产品分组" :rules="[{ required: true, message: '请选择产品分组'}]">
        <el-col :span="8">
          <el-select
            v-model="dataForm.tagList"
            multiple
            style="width: 250px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in this.tags"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-col>
      </el-form-item> -->
      <el-form-item
        label="产品名称"
        prop="prodName"
        :rules="[
          { required: true, message: '产品名称不能为空'},
          { pattern: /\s\S+|S+\s|\S/, message: '请输入正确的产品名称', trigger: 'blur' }
        ]"
      >
        <el-col :span="8">
          <el-input
            v-model="dataForm.prodName"
            placeholder="产品名称"
            maxlength="50"
          />
        </el-col>
      </el-form-item>
      <el-form-item
        label="产品卖点"
        prop="brief"
        :rules="[
          { required: false, pattern: /\s\S+|S+\s|\S/, message: '请输入正确的产品卖点', trigger: 'blur' }
        ]"
      >
        <el-col :span="8">
          <el-input
            v-model="dataForm.brief"
            type="textarea"
            :autosize="{minRows: 2, maxRows: 4}"
            placeholder="产品卖点"
          />
        </el-col>
      </el-form-item>
      <!-- <el-form-item label="配送方式">
        <el-checkbox v-model="dataForm.deliveryMode.hasShopDelivery">商家配送</el-checkbox>
        <el-checkbox v-model="dataForm.deliveryMode.hasUserPickUp">用户自提</el-checkbox>
      </el-form-item>
      <prod-transport
        v-show="dataForm.deliveryMode.hasShopDelivery"
        v-model="dataForm.deliveryTemplateId"
      /> -->

      <el-form-item label="折射率">
        <el-select v-model="dataForm.zslList" multiple filterable default-first-option placeholder="请选择" @change="handleTagClick">
          <el-option
            v-for="item in zslListValues"
            :key="item.valueId"
            :label="item.propValue"
            :value="item.propValue"
          />
        </el-select>
      </el-form-item>

      <!-- <sku-tag
        ref="skuTag"
        :sku-list="dataForm.skuList"
        @change="skuTagChangeSkuHandler"
      /> -->
      <sku-table
        ref="skuTable"
        :table-value="dataForm.properties"
      />

      <el-form-item label="特殊加工">
        <el-button size="mini" @click="addTsjg">添加</el-button>
        <template v-for="(zslItem,zslIndex) in dataForm.tsjg">
          <el-row :key="zslIndex+'zsl'">
            <el-col :span="8">
              <el-select v-model="zslItem.type" placeholder="请选择">
                <el-option
                  v-for="item in specialList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select v-model="zslItem.conditions" placeholder="请选择">
                <el-option
                  v-for="item in conditionList"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-input v-model="zslItem.price" style="width:140px" placeholder="请输入价格" />

              <el-button style="marginLeft:10px" size="mini" @click="delTsjg(zslIndex)">删除</el-button>
            </el-col>
          </el-row>
        </template>

      </el-form-item>
      <el-form-item
        label="产品详情"
        prop="content"
      >
        <tiny-mce
          ref="content"
          v-model="dataForm.content"
          style="width:1000px"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="dataFormSubmit()"
        >确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { treeDataTranslate, idList } from '@/utils'
import MulPicUpload from '@/components/mul-pic-upload'
import SkuTable from './sku-table'
import TinyMce from '@/components/tiny-mce'

import { Debounce } from '@/utils/debounce'
import prodApi from '@/api/prod'
import brandApi from '@/api/brand'
import enumApi from '@/api/enum'
export default {
  components: {
    MulPicUpload,
    TinyMce,
    SkuTable

  },
  data() {
    return {
      // 分类树展示与回显
      category: {
        list: [],
        selected: [],
        props: {
          value: 'categoryId',
          label: 'categoryName'
        }
      },
      // 规格列表
      dataForm: {
        prodName: '',
        brief: '',
        pic: '',
        imgs: '',
        categoryId: 0,
        prodId: 0,
        properties: [],
        content: '',
        status: 1,
        brandId: null,
        deliveryMode: {
          hasShopDelivery: false,
          hasUserPickUp: false
        },
        deliveryTemplateId: null,
        tsjg: []
      },
      tags: [],
      resourcesUrl: process.env.VUE_APP_RESOURCES_URL,
      brandList: [],
      zslListValues: [],
      specialList: [],

      conditionList: []
    }
  },
  computed: {
    defalutSku() {
      return this.$store.state.prod.defalutSku
    }
  },
  activated() {

  },
  mounted() {
    this.getbrandList()
    this.dataForm.prodId = this.$route.query.prodId
    this.getDataList()
    this.prodSpecListSpecValueById()
    this.enumSpecialProcess()
    this.enumSpecialCondition()
  },
  methods: {
    delTsjg(index) {
      this.dataForm.tsjg.splice(index, 1)
    },
    addTsjg() {
      const data = {
        type: null,
        conditions: null,
        price: ''
      }
      this.dataForm.tsjg.push(data)
    },
    enumSpecialCondition() {
      enumApi.enumSpecialCondition().then((res) => {
        this.conditionList = res.data
      })
    },
    enumSpecialProcess() {
      enumApi.enumSpecialProcess().then((res) => {
        this.specialList = res.data
      })
    },
    prodSpecListSpecValueById() {
      prodApi.prodSpecListSpecValueById(6).then(({ data }) => {
        this.zslListValues = data
      })
    },
    // 获取分类数据
    getDataList() {
      console.log('this.dataForm.prodId------>', this.dataForm)
      if (this.dataForm.prodId) {
        // 获取产品数据
        prodApi.getProdInfoById(this.dataForm.prodId).then(({ data }) => {
          this.dataForm = data
          this.dataForm.status = data.status ? 1 : 0

          const properties = data.properties || []
          const zslList = []
          properties.forEach((item) => {
            zslList.push(item.zsl)
          })
          this.dataForm.zslList = zslList
          console.log('data.skuList----this.dataForm->', this.dataForm)
          // this.$refs.skuTag.init(data.skuList)
          // this.$refs.skuTable.init()
          // this.category.selected = idList(this.category.list, this.dataForm.categoryId, 'categoryId', 'children').reverse()
          // this.dataForm.tagList = data.tagList
        })
      } else {
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          this.dataForm.pic = ''
          this.dataForm.imgs = ''
        })
      }

      // this.getCategoryList().then(() => {
      //   if (this.dataForm.prodId) {
      //     // 获取产品数据
      //     prodApi.getProdInfoById().then(({ data }) => {
      //       this.dataForm = data
      //       this.dataForm.deliveryMode = JSON.parse(data.deliveryMode)
      //       this.$refs.skuTag.init(data.skuList)
      //       this.$refs.skuTable.init()
      //       this.category.selected = idList(this.category.list, this.dataForm.categoryId, 'categoryId', 'children').reverse()
      //       this.dataForm.tagList = data.tagList
      //     })
      //   } else {
      //     this.$nextTick(() => {
      //       this.$refs['dataForm'].resetFields()
      //       this.$refs.skuTag.init()
      //       this.dataForm.pic = ''
      //       this.dataForm.imgs = ''
      //     })
      //   }
      // })
    },
    getbrandList() {
      brandApi.brandList().then((res) => {
        this.brandList = res.data
      })
    },
    // 获取分类信息
    getCategoryList() {
      return prodApi.listCategory(
      ).then(({ data }) => {
        this.category.list = treeDataTranslate(data, 'categoryId', 'parentId')
      })
    },
    // 选择分类改变事件
    // handleCategoryChange(val) {
    //   this.dataForm.categoryId = val[val.length - 1]
    // },
    // 表单提交
    dataFormSubmit: Debounce(function() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return
        }
        if (!this.dataForm.imgs) {
          this.errorMsg('请选择图片上传')
          return
        }

        const param = Object.assign({}, this.dataForm)
        // 设置价格和库存
        // this.paramSetPriceAndStocks(param)

        param.deliveryMode = undefined
        param.deliveryModeVo = this.dataForm.deliveryMode
        // 商品主图
        param.pic = this.dataForm.imgs.split(',')[0]
        prodApi.prodProd({
          method: param.prodId ? 'put' : 'post',
          data: param
        }).then(({ data }) => {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.visible = false
              // this.$store.commit('common/removeMainActiveTab')
              // this.$router.push({ name: 'prod-prodList' })
              this.$emit('refreshDataList')
            }
          })
        })
      })
    }),
    skuTagChangeSkuHandler(skuList) {
      // const prodName = this.dataForm.prodName
      // skuList.forEach(sku => {
      //   if (sku.properties) {
      //     sku.skuName = ''
      //     const properties = sku.properties.split(';')
      //     for (const propertiesKey in properties) {
      //       sku.skuName += properties[propertiesKey].split(':')[1] + ' '
      //     }
      //     sku.prodName = prodName + ' ' + sku.skuName
      //   }
      // })
      this.dataForm.skuList = skuList
    },
    handleTagClick() {
      const tagList = []
      console.log('handleTagClick-----xx--1->', this.dataForm.zslList)
      this.dataForm.zslList.forEach((item, index) => {
        let tagData = {
          abs: '',
          tsb: null,
          yxbj: '',
          dzlxs: [],
          qmbj: 0,
          zsl: '',
          index: index,
          value: ''
        }

        tagData.zsl = item
        tagData.value = item

        this.dataForm.properties.forEach((subItem) => {
          if (subItem.zsl === tagData.zsl) {
            tagData = { ...subItem }
          }
        })
        tagList.push(tagData)
      })
      console.log('handleTagClick-----xx--2->', tagList)
      this.dataForm.properties = tagList
    },
    errorMsg(message) {
      this.$message({
        message: message,
        type: 'error',
        duration: 1500
      })
    }
  }
}
</script>
